<template>
  <div class="system-container">
    <el-tabs v-model="activeTab" class="system-tabs">
      <el-tab-pane label="系统参数" name="params">
        <el-card>
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><Setting /></el-icon>
                <span>系统参数设置</span>
              </div>
              <div class="header-actions">
                <el-button type="primary" @click="saveParams">
                  <el-icon><Check /></el-icon>
                  保存设置
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="params-form">
            <el-form :model="systemParams" label-width="180px" label-position="left">
              <el-divider content-position="left">基本参数</el-divider>
              
              <el-form-item label="系统维护模式">
                <el-switch
                  v-model="systemParams.maintenanceMode"
                  active-text="开启"
                  inactive-text="关闭"
                />
              </el-form-item>
              
              <el-form-item label="系统公告" v-if="systemParams.maintenanceMode">
                <el-input
                  v-model="systemParams.maintenanceMessage"
                  type="textarea"
                  :rows="3"
                  placeholder="系统维护公告内容"
                />
              </el-form-item>
              
              <el-form-item label="订单自动分配">
                <el-switch
                  v-model="systemParams.autoAssignOrder"
                  active-text="开启"
                  inactive-text="关闭"
                />
              </el-form-item>
              
              <el-form-item label="最大接单范围">
                <el-input-number
                  v-model="systemParams.maxOrderDistance"
                  :min="1"
                  :max="20"
                  :step="0.5"
                  :precision="1"
                > 
                  <template #append>公里</template>
                </el-input-number>
              </el-form-item>
              
              <el-divider content-position="left">费用设置</el-divider>
              
              <el-form-item label="基础价格">
                <el-input-number
                  v-model="systemParams.basePrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                > 
                  <template #append>元</template>
                </el-input-number>
              </el-form-item>
              
              <el-form-item label="每公里单价">
                <el-input-number
                  v-model="systemParams.pricePerKm"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                > 
                  <template #append>元/公里</template>
                </el-input-number>
              </el-form-item>
              
              <el-form-item label="等待费用">
                <el-input-number
                  v-model="systemParams.waitingPrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                > 
                  <template #append>元/分钟</template>
                </el-input-number>
              </el-form-item>
              
              <el-form-item label="平台服务费比例">
                <el-input-number
                  v-model="systemParams.serviceFeeRate"
                  :min="0"
                  :max="30"
                  :precision="1"
                  :step="0.5"
                > 
                  <template #append>%</template>
                </el-input-number>
              </el-form-item>
              
              <el-divider content-position="left">安全设置</el-divider>
              
              <el-form-item label="行程异常速度阈值">
                <el-input-number
                  v-model="systemParams.speedThreshold"
                  :min="30"
                  :max="120"
                  :step="5"
                > 
                  <template #append>公里/小时</template>
                </el-input-number>
              </el-form-item>
              
              <el-form-item label="位置上报频率">
                <el-input-number
                  v-model="systemParams.locationUpdateInterval"
                  :min="5"
                  :max="60"
                  :step="5"
                > 
                  <template #append>秒</template>
                </el-input-number>
              </el-form-item>
              
              <el-form-item label="行程偏离预警距离">
                <el-input-number
                  v-model="systemParams.routeDeviationThreshold"
                  :min="100"
                  :max="2000"
                  :step="100"
                > 
                  <template #append>米</template>
                </el-input-number>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="系统日志" name="logs">
        <el-card>
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><Document /></el-icon>
                <span>系统日志</span>
              </div>
              <div class="header-actions">
                <el-select v-model="logLevel" placeholder="日志级别" style="width: 120px; margin-right: 10px;">
                  <el-option label="全部" value="all" />
                  <el-option label="信息" value="info" />
                  <el-option label="警告" value="warning" />
                  <el-option label="错误" value="error" />
                </el-select>
                <el-date-picker
                  v-model="logDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 150px; margin-right: 10px;"
                />
                <el-button type="primary" @click="searchLogs">
                  <el-icon><Search /></el-icon>
                  查询
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="logs-list" v-loading="logsLoading">
            <el-table
              :data="logsList"
              stripe
              border
              style="width: 100%"
            >
              <el-table-column prop="timestamp" label="时间" width="180" sortable />
              <el-table-column prop="level" label="级别" width="100">
                <template #default="scope">
                  <el-tag 
                    :type="scope.row.level === 'info' ? 'info' : scope.row.level === 'warning' ? 'warning' : 'danger'"
                  >
                    {{ scope.row.level === 'info' ? '信息' : scope.row.level === 'warning' ? '警告' : '错误' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="module" label="模块" width="120" />
              <el-table-column prop="message" label="内容" />
              <el-table-column prop="ip" label="IP地址" width="140" />
              <el-table-column prop="user" label="操作人" width="120" />
            </el-table>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="logsCurrentPage"
                v-model:page-size="logsPageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="logsTotal"
                @size-change="handleLogsSizeChange"
                @current-change="handleLogsCurrentChange"
              />
            </div>
          </div>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="数据备份" name="backup">
        <el-card>
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><Download /></el-icon>
                <span>数据备份</span>
              </div>
              <div class="header-actions">
                <el-button type="primary" @click="createBackup">
                  <el-icon><Plus /></el-icon>
                  创建备份
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="backup-list" v-loading="backupLoading">
            <el-table
              :data="backupsList"
              stripe
              border
              style="width: 100%"
            >
              <el-table-column prop="id" label="备份ID" width="100" />
              <el-table-column prop="createTime" label="创建时间" width="180" sortable />
              <el-table-column prop="type" label="备份类型" width="120">
                <template #default="scope">
                  <el-tag>{{ scope.row.type === 'auto' ? '自动备份' : '手动备份' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="fileSize" label="文件大小" width="120" />
              <el-table-column prop="operatorName" label="操作人" width="120" />
              <el-table-column prop="remark" label="备注" />
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button 
                    size="small" 
                    type="primary"
                    @click="downloadBackup(scope.row)"
                  >
                    下载
                  </el-button>
                  <el-button 
                    size="small" 
                    type="success"
                    @click="restoreBackup(scope.row)"
                  >
                    恢复
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger"
                    @click="deleteBackup(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="系统通知" name="notifications">
        <el-card>
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon><Bell /></el-icon>
                <span>系统通知</span>
              </div>
              <div class="header-actions">
                <el-button type="primary" @click="showCreateNotificationDialog">
                  <el-icon><Plus /></el-icon>
                  发送通知
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="notification-list" v-loading="notificationLoading">
            <el-table
              :data="notificationsList"
              stripe
              border
              style="width: 100%"
            >
              <el-table-column prop="id" label="通知ID" width="100" />
              <el-table-column prop="title" label="标题" width="200" />
              <el-table-column prop="content" label="内容" show-overflow-tooltip />
              <el-table-column prop="type" label="类型" width="120">
                <template #default="scope">
                  <el-tag :type="scope.row.type === 'all' ? 'primary' : scope.row.type === 'driver' ? 'success' : 'warning'">
                    {{ scope.row.type === 'all' ? '全部用户' : scope.row.type === 'driver' ? '司机' : '乘客' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="发送时间" width="180" sortable />
              <el-table-column prop="sender" label="发送人" width="120" />
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button 
                    size="small" 
                    @click="showNotificationDetail(scope.row)"
                  >
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="notificationCurrentPage"
                v-model:page-size="notificationPageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="notificationTotal"
                @size-change="handleNotificationSizeChange"
                @current-change="handleNotificationCurrentChange"
              />
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 发送通知对话框 -->
    <el-dialog
      v-model="notificationDialogVisible"
      title="发送系统通知"
      width="600px"
    >
      <el-form :model="notificationForm" label-width="100px" :rules="notificationRules" ref="notificationFormRef">
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="notificationForm.title" placeholder="请输入通知标题"></el-input>
        </el-form-item>
        <el-form-item label="接收对象" prop="type">
          <el-radio-group v-model="notificationForm.type">
            <el-radio label="all">全部用户</el-radio>
            <el-radio label="driver">所有司机</el-radio>
            <el-radio label="passenger">所有乘客</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="notificationForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入通知内容"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="notificationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sendNotification">发送</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 通知详情对话框 -->
    <el-dialog
      v-model="notificationDetailDialogVisible"
      title="通知详情"
      width="600px"
    >
      <div class="notification-detail" v-if="currentNotification">
        <h3 class="notification-title">{{ currentNotification.title }}</h3>
        <div class="notification-meta">
          <span>发送时间：{{ currentNotification.createTime }}</span>
          <span>发送人：{{ currentNotification.sender }}</span>
          <span>接收对象：
            <el-tag :type="currentNotification.type === 'all' ? 'primary' : currentNotification.type === 'driver' ? 'success' : 'warning'">
              {{ currentNotification.type === 'all' ? '全部用户' : currentNotification.type === 'driver' ? '司机' : '乘客' }}
            </el-tag>
          </span>
        </div>
        <div class="notification-content">
          {{ currentNotification.content }}
        </div>
        <div class="notification-stats">
          <div class="stats-item">
            <div class="stats-label">已发送</div>
            <div class="stats-value">{{ currentNotification.stats.sent }}</div>
          </div>
          <div class="stats-item">
            <div class="stats-label">已读</div>
            <div class="stats-value">{{ currentNotification.stats.read }}</div>
          </div>
          <div class="stats-item">
            <div class="stats-label">已读率</div>
            <div class="stats-value">{{ currentNotification.stats.readRate }}%</div>
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 创建备份对话框 -->
    <el-dialog
      v-model="backupDialogVisible"
      title="创建备份"
      width="500px"
    >
      <el-form :model="backupForm" label-width="100px">
        <el-form-item label="备份类型">
          <el-radio-group v-model="backupForm.type">
            <el-radio label="full">完整备份</el-radio>
            <el-radio label="data">仅数据</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="backupForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备份备注"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="backupDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBackup">确认备份</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 当前激活的标签页
const activeTab = ref('params')

// 系统参数设置
const systemParams = reactive({
  maintenanceMode: false,
  maintenanceMessage: '系统正在维护中，预计将于2小时后恢复，给您带来不便，敬请谅解。',
  autoAssignOrder: true,
  maxOrderDistance: 5.0,
  basePrice: 10.00,
  pricePerKm: 2.50,
  waitingPrice: 0.50,
  serviceFeeRate: 10.0,
  speedThreshold: 60,
  locationUpdateInterval: 10,
  routeDeviationThreshold: 500
})

// 保存系统参数
const saveParams = () => {
  // 模拟API请求
  // 在实际项目中，应该调用API保存参数
  
  ElMessage.success('系统参数已保存')
}

// 日志相关
const logLevel = ref('all')
const logDate = ref('')
const logsLoading = ref(false)
const logsCurrentPage = ref(1)
const logsPageSize = ref(10)
const logsTotal = ref(0)

// 日志数据
const logsList = ref([
  {
    timestamp: '2023-05-11 10:30:25',
    level: 'info',
    module: '订单系统',
    message: '新订单创建成功，订单号: O2023051105',
    ip: '192.168.1.100',
    user: '系统'
  },
  {
    timestamp: '2023-05-11 10:15:10',
    level: 'warning',
    module: '支付系统',
    message: '订单支付超时，订单号: O2023051104',
    ip: '192.168.1.100',
    user: '系统'
  },
  {
    timestamp: '2023-05-11 09:55:32',
    level: 'error',
    module: '用户系统',
    message: '用户登录失败，账号: user123，原因: 密码错误',
    ip: '192.168.1.105',
    user: '系统'
  },
  {
    timestamp: '2023-05-11 09:40:18',
    level: 'info',
    module: '司机系统',
    message: '司机状态变更: 上线，司机ID: D2023001',
    ip: '192.168.1.200',
    user: '张师傅'
  },
  {
    timestamp: '2023-05-11 09:30:45',
    level: 'info',
    module: '系统管理',
    message: '系统参数更新: 基础价格修改为 10.00 元',
    ip: '192.168.1.50',
    user: 'admin'
  }
])

// 搜索日志
const searchLogs = () => {
  logsLoading.value = true
  // 模拟API请求
  setTimeout(() => {
    // 这里实际项目中应该调用API
    logsLoading.value = false
    ElMessage.success('日志查询完成')
  }, 500)
}

// 处理日志分页大小变化
const handleLogsSizeChange = (val) => {
  logsPageSize.value = val
  searchLogs()
}

// 处理日志当前页变化
const handleLogsCurrentChange = (val) => {
  logsCurrentPage.value = val
  searchLogs()
}

// 计算日志总数
logsTotal.value = logsList.value.length

// 备份相关
const backupLoading = ref(false)
const backupDialogVisible = ref(false)
const backupForm = reactive({
  type: 'full',
  remark: ''
})

// 备份数据
const backupsList = ref([
  {
    id: 'B20230511001',
    createTime: '2023-05-11 00:00:00',
    type: 'auto',
    fileSize: '15.6 MB',
    operatorName: '系统',
    remark: '每日自动备份'
  },
  {
    id: 'B20230510001',
    createTime: '2023-05-10 10:15:30',
    type: 'manual',
    fileSize: '15.4 MB',
    operatorName: 'admin',
    remark: '系统参数更新前备份'
  },
  {
    id: 'B20230510002',
    createTime: '2023-05-10 00:00:00',
    type: 'auto',
    fileSize: '15.3 MB',
    operatorName: '系统',
    remark: '每日自动备份'
  }
])

// 创建备份
const createBackup = () => {
  backupForm.type = 'full'
  backupForm.remark = ''
  backupDialogVisible.value = true
}

// 确认备份
const confirmBackup = () => {
  backupLoading.value = true
  
  // 模拟API请求
  setTimeout(() => {
    // 这里实际项目中应该调用API创建备份
    
    // 添加新备份到列表
    const newBackup = {
      id: 'B' + new Date().getTime(),
      createTime: new Date().toLocaleString(),
      type: 'manual',
      fileSize: '15.7 MB',
      operatorName: 'admin',
      remark: backupForm.remark || `手动${backupForm.type === 'full' ? '完整' : '数据'}备份`
    }
    
    backupsList.value.unshift(newBackup)
    
    backupLoading.value = false
    backupDialogVisible.value = false
    ElMessage.success('备份创建成功')
  }, 1000)
}

// 下载备份
const downloadBackup = (backup) => {
  ElMessage.success(`正在下载备份: ${backup.id}`)
  // 在实际项目中，应该调用API下载备份文件
}

// 恢复备份
const restoreBackup = (backup) => {
  ElMessageBox.confirm(`确定要恢复备份 ${backup.id} 吗？此操作将覆盖当前数据，无法撤销！`, '警告', {
    confirmButtonText: '确定恢复',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API请求
    // 在实际项目中，应该调用API恢复备份
    
    ElMessage.success('备份恢复成功，系统将在1分钟后重启')
  }).catch(() => {})
}

// 删除备份
const deleteBackup = (backup) => {
  ElMessageBox.confirm(`确定要删除备份 ${backup.id} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API请求
    // 在实际项目中，应该调用API删除备份
    
    // 从列表中移除
    const index = backupsList.value.findIndex(b => b.id === backup.id)
    if (index !== -1) {
      backupsList.value.splice(index, 1)
    }
    
    ElMessage.success('备份已删除')
  }).catch(() => {})
}

// 通知相关
const notificationLoading = ref(false)
const notificationCurrentPage = ref(1)
const notificationPageSize = ref(10)
const notificationTotal = ref(0)

// 通知对话框
const notificationDialogVisible = ref(false)
const notificationFormRef = ref(null)
const notificationForm = reactive({
  title: '',
  type: 'all',
  content: ''
})

// 通知表单验证规则
const notificationRules = {
  title: [
    { required: true, message: '请输入通知标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度应为2-50个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择接收对象', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入通知内容', trigger: 'blur' },
    { min: 5, max: 500, message: '内容长度应为5-500个字符', trigger: 'blur' }
  ]
}

// 通知详情对话框
const notificationDetailDialogVisible = ref(false)
const currentNotification = ref(null)

// 通知数据
const notificationsList = ref([
  {
    id: 'N20230511001',
    title: '系统维护通知',
    content: '尊敬的用户，系统将于5月12日凌晨2:00-4:00进行系统升级维护，期间可能无法正常使用，请您提前安排好行程。',
    type: 'all',
    createTime: '2023-05-11 09:30:00',
    sender: 'admin',
    stats: {
      sent: 1000,
      read: 650,
      readRate: 65
    }
  },
  {
    id: 'N20230510001',
    title: '司机接单范围调整',
    content: '尊敬的司机，平台已将最大接单范围调整为5公里，请您注意查看并合理安排接单。',
    type: 'driver',
    createTime: '2023-05-10 14:15:00',
    sender: 'admin',
    stats: {
      sent: 200,
      read: 180,
      readRate: 90
    }
  },
  {
    id: 'N20230509001',
    title: '乘客优惠活动',
    content: '尊敬的乘客，平台5月9日至5月15日开展校园出行优惠活动，每单减免5元，最高可减20元，多乘多惠，欢迎参与！',
    type: 'passenger',
    createTime: '2023-05-09 10:00:00',
    sender: 'admin',
    stats: {
      sent: 800,
      read: 720,
      readRate: 90
    }
  }
])

// 计算通知总数
notificationTotal.value = notificationsList.value.length

// 显示创建通知对话框
const showCreateNotificationDialog = () => {
  notificationForm.title = ''
  notificationForm.type = 'all'
  notificationForm.content = ''
  notificationDialogVisible.value = true
}

// 发送通知
const sendNotification = async () => {
  try {
    await notificationFormRef.value.validate()
    
    // 模拟API请求
    // 在实际项目中，应该调用API发送通知
    
    // 添加新通知到列表
    const newNotification = {
      id: 'N' + new Date().getTime(),
      title: notificationForm.title,
      content: notificationForm.content,
      type: notificationForm.type,
      createTime: new Date().toLocaleString(),
      sender: 'admin',
      stats: {
        sent: notificationForm.type === 'all' ? 1000 : notificationForm.type === 'driver' ? 200 : 800,
        read: 0,
        readRate: 0
      }
    }
    
    notificationsList.value.unshift(newNotification)
    
    notificationDialogVisible.value = false
    ElMessage.success('通知发送成功')
    
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 显示通知详情
const showNotificationDetail = (notification) => {
  currentNotification.value = notification
  notificationDetailDialogVisible.value = true
}

// 处理通知分页大小变化
const handleNotificationSizeChange = (val) => {
  notificationPageSize.value = val
}

// 处理通知当前页变化
const handleNotificationCurrentChange = (val) => {
  notificationCurrentPage.value = val
}

// 组件挂载后执行
onMounted(() => {
  // 获取系统参数
})
</script>

<style scoped>
.system-container {
  padding: 20px;
}

.system-tabs {
  min-height: calc(100vh - 60px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.header-title .el-icon {
  margin-right: 8px;
  font-size: 20px;
}

.params-form {
  max-width: 800px;
  margin: 0 auto;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.notification-title {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
}

.notification-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
  color: #909399;
  font-size: 14px;
}

.notification-content {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  line-height: 1.6;
}

.notification-stats {
  display: flex;
  border-top: 1px solid #EBEEF5;
  padding-top: 15px;
}

.stats-item {
  flex: 1;
  text-align: center;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.stats-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}
</style> 